package com.liu.webstore.advice;

import com.liu.webstore.common.Constant;
import com.liu.webstore.util.WebstoreUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author LiuYumei
 * @Date 2022/7/31 21:07
 * <p>
 * annotations = Controller.class表示只会扫描带有Controller注解的bean
 */
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {
    private static final Logger log = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler({Exception.class})
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 打印异常的概括
        log.error("服务器发生异常：{}", e.getMessage());
        // 打印异常栈的详细信息
        for (StackTraceElement element : e.getStackTrace()) {
            log.error(element.toString());
        }
        // 给浏览器响应，首先判断是 普通请求 还是 异步请求
        String xRequestedWith = request.getHeader("x-requested-with");
        // XMLHttpRequest表示异步请求
        if (Constant.XML_HTTP_REQUEST.equals(xRequestedWith)) {
            // 设置响应的内容类型：普通类型（plain，如果要返回JSON类型，则需要改成application/json），字符集为utf-8
            response.setContentType("application/plain;charset=utf-8");
            // 获取输出流输出字符串
            PrintWriter writer = response.getWriter();
            writer.write(WebstoreUtil.getJsonString(500, "服务器异常！"));
        } else {
            response.sendRedirect(request.getContextPath() + "/home/error");
        }
    }
}
